import {
    createRouter,
    createWebHashHistory
} from 'vue-router'
import Home from '../Home.vue'
import constants from '../constants'

const routes = [{
        path: '/',
        name: "Home",
        component: Home
    },
    {
        path: '/result/:id', //这里改为路径传参
        name: 'Result',
        component: () => import( /*webChunkName: "Result"*/ '../result.vue')
    },
    {
        path: '/list',
        name: "List",
        component: () => import( /*webpackChunkName: "List"*/ '../HistoryList.vue')
    },
    {
        path: '/login',
        name: "Login",
        component: () => import( /*webpackChunkName: "Login"*/ '../login.vue')
    },
    {
        path: '/success',
        name: "Success",
        component: () => import( /*webpackChunkName: "Login"*/ '../success.vue')
    },
    {
        path: '/noPermission',
        name: "NoPermission",
        component: () => import( /*webpackChunkName: "Login"*/ '../NoPermission.vue')
    }
]
const router = createRouter({
    history: createWebHashHistory(), //采用hash模式的路由
    routes
})

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem(constants.Token)
    if (token || to.name === 'Login') {
        let user = localStorage.getItem(constants.UserInfo);
        const roleList = user ? JSON.parse(user).role : [];
        if (to.name === "Login" || (roleList.length && roleList.includes(to.name))) {
            next()
        } else {
            next('/noPermission')
        }
        next();
    } else {
        next('/login')
    }
})

export default router;